import json
import logging

import requests
from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.user.models import User
from utils.response_code import RETCODE
from utils.user_info_response import user_info_response

logger = logging.getLogger('django')


class Test(View):
    """
    测试接口
    """

    def get(self, request):
        return http.JsonResponse({'code': RETCODE.OK})


class Users(View):
    """
    用户
    """

    def post(self, request):
        """登录患者信息"""
        data = json.loads(request.body.decode())
        code = data.get('js_code')
        head_img = data.get('avatarUrl')
        nick_name = data.get('nickName')
        try:
            r = requests.get(
                'https://api.weixin.qq.com/sns/jscode2session?appid=wx0dc7d196b3eb62da&secret=7641d74faa9325869f8e08da8a209c81&js_code=' + code + '&grant_type=authorization_code')
            r_dict = json.loads(str(r._content, 'utf-8'))
            data_dict = {
                'code_response': r_dict,
                'head_img': head_img,
                'nick_name': nick_name
            }
            if User.objects.get(token=r_dict['openid']):
                return http.JsonResponse({'code': RETCODE.OK, 'success': data_dict, 'errmsg': 'success'})
            else:
                User.objects.create(token=r_dict['openid'], name=nick_name)
                return http.JsonResponse({'code': RETCODE.OK, 'success': data_dict, 'errmsg': 'success'})

            # return http.JsonResponse({'code': RETCODE.OK, 'success': data_dict, 'errmsg': 'success'})
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.OPENIDERR, 'errmsg': '获取openid失败'})

    def get(self, request):
        """查询患者信息"""
        phone = request.GET.get('phone')
        token = request.GET.get('token')
        id = request.GET.get('id')
        if phone:
            res = user_info_response(phone, 'phone')
        elif token:
            res = user_info_response(token, 'token')
        elif id:
            res = user_info_response(id, 'id')
        if res['code'] != 'error':
            return http.JsonResponse({'code': RETCODE.OK, 'data': res['data'], 'errmsg': 'success'})
        else:
            return http.JsonResponse({'code': RETCODE.NODATAERR, 'errmsg': res['data']})

    def put(self, request):
        """修改患者信息"""
        token = json.loads(request.body.decode()).get('token')
        new_name = request.GET.get('new_name')
        # new_sex = request.GET.get('new_sex')
        new_sex = User.objects.get(token=token).sex if request.GET.get('new_sex') == '' else request.GET.get('new_sex')
        new_age = User.objects.get(token=token).age if request.GET.get('new_sex') == '' else request.GET.get('new_age')
        new_phone = User.objects.get(token=token).phone if request.GET.get('new_sex') == '' else request.GET.get(
            'new_phone')
        # new_sex = User.objects.get(token=token).sex if new_sex == '' else new_sex

        if not token:
            return http.JsonResponse({'code': RETCODE.NECESSARYPARAMERR, 'errmsg': '未传递token'})
        else:
            try:
                User.objects.filter(token=token).update(
                    name=new_name,
                    sex=new_sex,
                    age=new_age,
                    phone=new_phone
                )
                # res = user_info_response('1840707264', 'token')
                res = user_info_response(token, 'token')

                return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改成功', 'data': res['data']})
            except Exception as e:
                logger.error(e)
                return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '修改失败'})
